package com.smartrobot.smartrobot.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.SmartRobotApplication;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.util.HanziToPinyin;
import com.github.siyamed.shapeimageview.CircularImageView;
import com.huanxinapi.activity.BaseActivity;
import com.huanxinapi.activity.Constant;
import com.smartrobot.smartrobot.Common.CommonFunc;
import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.util.*;
import com.smartrobot.smartrobot.view.ToastCustom;


public class LoginActivity extends BaseActivity implements OnClickListener{

    public static Activity activity;
    CircularImageView photo;
	ImageView canSeePassword;
	EditText account,password;
    ImageView login;
	TextView newAccount;
    private LinearLayout login_progress;
    private LoginHandler handler;

    boolean isLogining = false;
    boolean isPressLogin = false;
    private final int LONGIN_HUANXIN_OK = 1111;
    private final int LONGIN_HUANXIN_FAILD = 1112;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        if(savedInstanceState != null){
            throw new NullPointerException();
        }
		this.setContentView(R.layout.page_login);
		

        SmartRobotApplication.getInstance().logout(null);
		init();

//		mNotificationManager.cancel(R.id.startServer);
	}

	public void init(){
		
		HttpUtil.init(getApplicationContext());
        activity = this;
		initView();
        handler = new LoginHandler();
	}
	
	public void initView(){
		photo = (CircularImageView)findViewById(R.id.login_photo);
		canSeePassword = (ImageView)findViewById(R.id.login_canSeePassword);
		account = (EditText)findViewById(R.id.login_account);
		password = (EditText)findViewById(R.id.login_password);
		login = (ImageView)findViewById(R.id.login_login);
		newAccount = (TextView)findViewById(R.id.login_newAccount);
        login_progress = (LinearLayout)findViewById(R.id.login_progress);
		
		login.setOnClickListener(this);
		newAccount.setOnClickListener(this);
		canSeePassword.setOnClickListener(this);

//        account.setText("18925961234");
//        password.setText("123456");

	}
	
	@Override
	public void onClick(View v) {
		
		if(v.getId() == login.getId()){//点击登录
			
			switch(legalLogin()){
			
			case 1:
				break;
			case 2:
				ToastCustom.showToast(getApplicationContext(), "账号或密码错误!");
				break;
				
			case 3:
				ToastCustom.showToast(getApplicationContext(),"请打开网络!");
				break;
				
		    default:

		    	PeopleRegisterMsg msg = new PeopleRegisterMsg();
		    	msg.setPhone(account.getText().toString().trim());
		    	msg.setPwd(password.getText().toString().trim());

                if(!isLogining){
                    isLogining = true;
                    isPressLogin = true;
                    login_progress.setVisibility(View.VISIBLE);
                    InputMethodManager imm= (InputMethodManager) getSystemService(LoginActivity.this.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(LoginActivity.this.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    HttpUtil.apiLogin(getApplicationContext(),msg, handler);
                }

		    	
		    	break;
				
			}
			
		}

        // 点击了可以是否能够看见密码
		if (v.getId() == canSeePassword.getId()) {

			if (password.getTransformationMethod() == null)
				password
						.setTransformationMethod(HideReturnsTransformationMethod
								.getInstance());
			else {
				if (password.getTransformationMethod() instanceof PasswordTransformationMethod) {

					password
							.setTransformationMethod(HideReturnsTransformationMethod
									.getInstance());
				} else if (password.getTransformationMethod() instanceof HideReturnsTransformationMethod) {
					password
							.setTransformationMethod(PasswordTransformationMethod
									.getInstance());

				}
			}
            // 光标移回位置
			password.setSelection(password.getText().toString().trim()
					.length());
		}
		
		
		if(v.getId() == newAccount.getId()){//选择注册新账户
			
			LayoutInflater inflater = getLayoutInflater();
		    View layout = inflater.inflate(R.layout.page_login_chose_role,null);
		    final AlertDialog dialog = new AlertDialog.Builder(this).setView(layout).show();
            dialog.setCanceledOnTouchOutside(true);
		 
		    layout.findViewById(R.id.role_be_hairreset).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					System.out.println("注册成理发师");
					Intent intent = new Intent();
					intent.setClass(LoginActivity.this, RegisterActivity.class);
					intent.putExtra("role", 0);
					startActivity(intent);
					dialog.dismiss();
					
					
				}
			});
		    layout.findViewById(R.id.role_be_user).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					System.out.println("注册成为客户");
					Intent intent = new Intent();
					intent.setClass(LoginActivity.this, RegisterActivity.class);
					intent.putExtra("role", 1);
					startActivity(intent);
					dialog.dismiss();
					
				}
			});;
		 
			
		}
		
	}
	
	int legalLogin(){
		
		System.out.println("---"+account.getText().toString().trim().length()+"--");
		
		if(account.getText().toString().trim().length() == 0  || password.getText().toString().trim().length() == 0)
			return 1;
		if(account.getText().toString().trim().length() > 20 || password.getText().toString().trim().length() > 12)
			return 2;
		if(!NetWorkUtil.isHasNetWork(getApplicationContext()))
			return 3;
		
		
		return 10;
	}
	

	@Override  
    public boolean onTouchEvent(MotionEvent event) {  
        // TODO Auto-generated method stub  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
            System.out.println("down");  
            if (LoginActivity.this.getCurrentFocus() != null) {  
                if (LoginActivity.this.getCurrentFocus().getWindowToken() != null) {  
                	InputMethodManager imm= (InputMethodManager) getSystemService(LoginActivity.this.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(LoginActivity.this.getCurrentFocus().getWindowToken(),  
                            InputMethodManager.HIDE_NOT_ALWAYS);  
                }  
            }  
        }  
        return super.onTouchEvent(event);  
    } 
	
	class LoginHandler extends Handler{
		@Override
		public void dispatchMessage(Message msg) {
			
			if(msg.what == HttpUtil.LOGIN_SUCCESS){



//                socketUtil.initSocket_2(getApplicationContext());

               final String  account = User.getInstance().getPhone();
                final String  password = CommonFunc.stringToMD5(account);
                // 调用sdk登陆方法登陆聊天服务器
                EMChatManager.getInstance().login(account, password, new EMCallBack() {

                    @Override
                    public void onSuccess() {

                        // 登陆成功，保存用户名密码
                        SmartRobotApplication.getInstance().setUserName(account);
                        SmartRobotApplication.getInstance().setPassword(password);
                        try {
                            // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                            // ** manually load all local groups and
                            // conversations in case we are auto login
                            EMGroupManager.getInstance().loadAllGroups();
                            EMChatManager.getInstance().loadAllConversations();

                            // demo中简单的处理成每次登陆都去获取好友username，开发者自己根据情况而定
//                            List<String> usernames = EMContactManager.getInstance().getContactUserNames();
//                            EMLog.d("roster", "contacts size: " + usernames.size());
//                            Map<String,  com.huanxinapi.activity.User> userlist = new HashMap<String,  com.huanxinapi.activity.User>();
//                            for (String username : usernames) {
//                                com.huanxinapi.activity.User user = new com.huanxinapi.activity.User();
//                                user.setUsername(username);
//                                setUserHearder(username, user);
//                                userlist.put(username, user);
//                            }
//                            // 存入内存
//                            SmartRobotApplication.getInstance().setContactList(userlist);
//                            // 存入db
//                            UserDao dao = new UserDao(LoginActivity.this);
//                            List< com.huanxinapi.activity.User> users = new ArrayList< com.huanxinapi.activity.User>(userlist.values());
//                            dao.saveContactList(users);
//
//                            // 获取群聊列表(群聊里只有groupid和groupname等简单信息，不包含members),sdk会把群组存入到内存和db中
//                            EMGroupManager.getInstance().getGroupsFromServer();
                        } catch (Exception e) {
                            e.printStackTrace();
                            //取好友或者群聊失败，不让进入主页面，也可以不管这个exception继续进到主页面
                            return;
                        }
                        //更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                        boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(SmartRobotApplication.currentUserNick.trim());
                        if (!updatenick) {
                            Log.e("LoginActivity", "update current user nick fail");
                        }

//                        Log.e("================================>","登录成功");

                        Message msg = new Message();
                        msg.what = LONGIN_HUANXIN_OK;
                        handler.sendMessage(msg);


                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(final int code, final String message) {

                        Message msg = new Message();
                        msg.what = LONGIN_HUANXIN_FAILD;
                        handler.sendMessage(msg);

                    }
                });


//				intent.setClass(LoginActivity.this,MainActivity.class );
//				startActivity(intent);
//				LoginActivity.this.finish();

			}

			if(msg.what == HttpUtil.LOGIN_FAILD){
                isLogining = false;
                login_progress.setVisibility(View.GONE);
                if(msg.obj != null){
                    if(msg.obj.equals("106"))
                        ToastCustom.showToast(LoginActivity.this, "账号或密码错误!");
                    else
                        ToastCustom.showToast(LoginActivity.this, "登陆服务器失败，请稍后再试");
                }
                else
                    ToastCustom.showToast(LoginActivity.this, "登陆服务器失败，请稍后再试");
			}

            if(msg.what == LONGIN_HUANXIN_OK){
                // 进入主页面
                if(isPressLogin){
                isPressLogin = false;
                User.getInstance().setIsLogin(true);//这就意味着可以跳过登录界面
                User.saveUserInfo(getApplicationContext());
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                Log.e("======> 主界面登录 ========>","              ");
                LoginActivity.this.finish();
                isLogining = false;
                }

            }

            if(msg.what == LONGIN_HUANXIN_FAILD){

                isLogining = false;
                ToastCustom.showToast(getApplicationContext(),"连接服务器失败，请稍后再试!");
                login_progress.setVisibility(View.GONE);

            }
			 
		}
	}

    /**
     * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
     *
     * @param username
     * @param user
     */
    protected void setUserHearder(String username, com.huanxinapi.activity.User user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) { //成为后台程序
            moveTaskToBack(true);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }




}
